import * as d3 from "d3";

export class WaveView {
  constructor({ el, width, height, frameSize, step, speedRatio, strokeStyle }) {
    this.el = el;
    this.width = width;
    this.height = height;
    this.frameSize = frameSize;
    this.step = step;
    this.speedRatio = speedRatio;
    this.strokeStyle = strokeStyle;

    this.queue = [];
    this.currentX = 0;
    this.lastX = 0;
    this.lastY = this.height / 2;

    this.setup();
  }

  setup() {
    this.svg = d3
      .select(this.el)
      .append("svg")
      .attr("width", this.width)
      .attr("height", this.height);

    this.svgPath = this.svg
      .append("path")
      .attr("fill", "none")
      .attr("stroke", this.strokeStyle);

    this.xScale = d3.scaleLinear().range([0, this.width]);
    this.yScale = d3.scaleLinear().range([this.height, 0]);
  }

  draw() {
    const line = d3
      .line()
      .x((d, i) => this.xScale(i))
      .y((d) => this.yScale(d));

    this.xScale.domain([0, this.queue.length]);
    this.yScale.domain(d3.extent(this.queue));

    this.svgPath.datum(this.queue).attr("d", line);
  }

  addData(arr) {
    this.queue.push(...arr);
    if (this.queue.length > this.frameSize) {
      this.queue.splice(0, this.queue.length - this.frameSize);
    }

    this.draw();
  }

  close() {
    this.queue = [];

    this.svg.selectAll("*").remove();
  }
}